package com.aluka.nirvana.framework.security.utils;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aluka.nirvana.framework.security.constant.ResultJsonKey;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author gongli
 * @since 2020/4/10 13:32
 */
public class ResponseUtils {

    /**
     * 将响应内容封装至响应体
     * @param response 响应体
     * @param status 响应状态
     * @param message 提示信息
     * @throws IOException 响应异常
     */
    public static void writeResponse(HttpServletResponse response, HttpStatus status, String message) throws IOException {
        JSONObject responseJson = new JSONObject();
        responseJson.put(ResultJsonKey.STATUS, status.value());
        responseJson.put(ResultJsonKey.MSG, message);
        writeResponse(response, responseJson);
    }

    /**
     * 将响应内容封装至响应体
     * @param response 响应体
     * @param body 响应内容
     * @throws IOException 响应异常
     */
    public static void writeResponse(HttpServletResponse response, Object body) throws IOException {
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Pragma", "no-cache");
        response.getWriter().write(JSONUtil.toJsonStr(body));
    }

}
